#include "netdb.h"
#include "netinet/in.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "unistd.h"

#define HOSTLEN 256
#define BACKLOG 1

int make_server_socket_q(char *, int, int);
int make_server_socket(char *ip, int portnum) {
  return make_server_socket_q(ip, portnum, BACKLOG);
}

int make_server_socket_q(char *ip, int portnum, int backlog) {
  struct sockaddr_in saddr;
  struct hostent *hp;
  char hostname[HOSTLEN];
  int sock_id;

  sock_id = socket(PF_INET, SOCK_STREAM, 0);
  if (sock_id == -1) {
    return -1;
  }

  saddr.sin_port = htons(portnum);
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = inet_addr(ip);

  if (bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) != 0) {
    return -1;
  }

  if (listen(sock_id, backlog) != 0) {
    return -1;
  }

  return sock_id;
}

int connnect_to_server(char *host, int portnum) {
  int sock;
  struct sockaddr_in servadd;
  struct hostent *hp;

  // step: get a socket
  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock == -1) {
    return -1;
  }

  // step 2: connect to server
  servadd.sin_port = htons(portnum);
  servadd.sin_family = AF_INET;
  servadd.sin_addr.s_addr = inet_addr(host);
  if (connect(sock, (struct sockaddr *)&servadd, sizeof(servadd)) != 0) {
    return -1;
  }

  return sock;
}